import ProvinceCityCountry from "@/pages/merchant/Address/Add/ProvinceCityCountry";
import { PHONE_REG } from "@/utils/pattern";
import { ProForm, ProFormCheckbox, ProFormInstance, ProFormSelect, ProFormText } from "@ant-design/pro-components";
import { Modal } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import styles from "./index.module.less";
import { getRegion } from "@/api/modules/user";
import { map, filter, omit } from "lodash";
import { addShopsAddressApi, getShopsAddressListApi } from "@/api/modules/merchant";
import { useRequest } from "ahooks";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import { saveDeliverAddress, saveReturnAddress } from "@/api/modules/transactionManagement";
import { DeliveryReturnValues } from "@/pages/merchant/Address/constant";

type Info = {
	visible: boolean;
	type: "deliver" | "return" | "";
	editData: any;
	isEdit: boolean;
};

export default forwardRef((props: any, ref) => {
	const { updateDetail, order_id, shop_id } = props;
	const [info, setInfo] = useState<Info>({
		visible: false,
		type: "",
		editData: null,
		isEdit: false
	});
	const formRef = useRef<ProFormInstance>();
	const [provinceOptions, setProvinceOptions] = useState<any[]>([]);
	const { loading, runAsync: addOrUpdateMerchantAddressApi } = useRequest(addShopsAddressApi, { manual: true });
	const { loading: loading1, runAsync } = useRequest(
		(type, data) => (type === "deliver" ? saveDeliverAddress : saveReturnAddress)(data),
		{
			manual: true
		}
	);

	useEffect(() => {
		getRegion({ pid: 0 }).then(res => {
			setProvinceOptions(
				map(res?.data, i => ({
					...i,
					isLeaf: false,
					disabled: true
				}))
			);
		});
	}, []);

	useEffect(() => {
		return () => {
			if (!info.visible) {
				formRef.current?.resetFields();
			}
		};
	}, [info.visible]);

	const handleOpen = (type: Info["type"], data: any) => {
		setInfo({ visible: true, type, editData: data, isEdit: Boolean(data) });
		setTimeout(() => {
			if (data) {
				formRef.current?.setFieldsValue({
					...data,
					info: {
						province: data.province,
						city: data.city,
						county: data.county
					}
				});
			}
		});
	};

	useImperativeHandle(ref, () => ({
		onOpen: handleOpen
	}));

	const handleClose = () => {
		setInfo({ visible: false, type: "", editData: null, isEdit: false });
	};

	const handleAddressSelectChange = (values: any) => {
		console.log(values, "<=============values")
		if (!info.isEdit) {
			setInfo(e => ({
				...e,
				editData: values
			}));
		}
		if (values) {
			formRef.current?.setFieldsValue({
				...values,
				info: {
					province: values.province,
					city: values.city,
					county: values.county
				}
			});
		}
	};

	const handleSubmit = () => {
		formRef.current?.validateFieldsReturnFormatValue?.().then(values => {
			const requestData = {
				...info.editData,
				...values,
				province: values.info?.province,
				city: values.info?.city,
				county: values.info?.county,
				shop_id,
				category: info.type === "deliver" ? DeliveryReturnValues.delivery : DeliveryReturnValues.return,
				is_default: info?.editData?.is_default ?? 0
			};
			console.log("===========values:", values, requestData, info);
			// addOrUpdateMerchantAddressApi(omit(requestData, ["label", "value", "info", "key", "title", "address_existing"])).then(
			// 	res => {
			// 		if (res?.code === RESULT_CODES.SUCCESS) {
			// 			runAsync(info.type, {
			// 				order_id,
			// 				[info.type === "deliver" ? "sender_address_id" : "return_address_id"]:
			// 					info.editData?.shop_return_addresses_id ?? info.editData?.address_id ?? res?.data?.shop_return_addresses_id
			// 			}).then(changeRes => {
			// 				if (changeRes?.code === RESULT_CODES.SUCCESS) {
			// 					handleClose();
			// 					updateDetail();
			// 				}
			// 			});
			// 		}
			// 	}
			// );
			runAsync(info.type, {
				order_id,
				[info.type === "deliver" ? "sender_address_id" : "return_address_id"]:
					values?.address_existing?.shop_return_addresses_id ||
					info.editData?.shop_return_addresses_id ||
					info.editData?.address_id
			}).then(res => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					handleClose();
					updateDetail();
				}
			});
		});
	};

	return (
		<Modal
			width={600}
			title={info.type === "return" ? "退货地址信息" : "发货地址信息"}
			open={info.visible}
			onCancel={handleClose}
			centered
			onOk={handleSubmit}
			okButtonProps={{
				loading: loading || loading1
			}}
		>
			<div className={styles.content}>
				<ProForm submitter={false} layout="horizontal" formRef={formRef} labelCol={{ span: 6 }}>
					<ProFormSelect
						label="从现有地址选择"
						name="address_existing"
						request={async () => {
							const res = await getShopsAddressListApi({ shop_id });
							return map(
								filter(res?.data ?? [], i => i?.category === (info.type === "deliver" ? 1 : 2)),
								i => ({
									...i,
									label: `${i?.company}-${i?.province}${i?.city}${i?.county}${i?.address}`,
									value: i?.shop_return_addresses_id
								})
							);
						}}
						fieldProps={{
							labelInValue: true,
							onChange: (value: any) => {
								handleAddressSelectChange(value);
							}
						}}
					/>
					<ProFormText
						placeholder={"请输入联系人"}
						label="联系人"
						disabled
						// rules={[{ required: true, message: "请输入联系人" }]}
						name="name"
					/>
					<ProFormText
						placeholder={"请输入手机号"}
						label="手机号"
						disabled
						rules={[
							// { required: true, message: "请输入手机号" },
							{ pattern: PHONE_REG, message: "请输入正确的手机号" }
						]}
						name="mobile"
					/>
					<ProForm.Item label="省市区" name="info">
						<ProvinceCityCountry provinceOptions={provinceOptions} disabled={true} />
					</ProForm.Item>
					<ProFormText label="详细地址" name="address" disabled placeholder={"请输入详细地址"} />
					{/* <ProFormCheckbox label="是否更新现有地址" name="is_update" /> */}
				</ProForm>
			</div>
		</Modal>
	);
});
